import React, { PureComponent } from 'react';
import { get } from 'lodash';
import PropTypes from 'prop-types';
import { Form, Input, Row, Col } from 'antd';
import { constants } from '@/utils';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

const { PRICE_MANGER_ACTION } = constants;
const ACTIONS = Object.keys(PRICE_MANGER_ACTION).map(key => PRICE_MANGER_ACTION[key]);

@Form.create()
class FormModal extends PureComponent {
  static propTypes = {
    action: PropTypes.oneOf(ACTIONS).isRequired,
    currentData: PropTypes.object,
    onFormModalRef: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.state = {
      globalDisabled: false,
    };
  }

  componentDidMount() {
    const { onFormModalRef } = this.props;
    if (onFormModalRef) {
      onFormModalRef(this);
    }
    this.initGlobalAction();
  }

  initGlobalAction = () => {
    const { action } = this.props;
    let globalDisabled = false;
    switch (action) {
      case PRICE_MANGER_ACTION.VIEW:
        globalDisabled = true;
        break;
      case PRICE_MANGER_ACTION.ADD:
        break;
      default:
    }
    this.setState({ globalDisabled });
  };

  getFormData = () => {
    const { form, currentData } = this.props;
    let data = null;
    form.validateFields((err, formData) => {
      if (err) {
        return;
      }
      data = {};
      Object.assign(data, currentData || {});
      Object.assign(data, formData);
    });
    return data;
  };

  render() {
    const { form, currentData } = this.props;
    const { globalDisabled } = this.state;
    const { getFieldDecorator } = form;
    getFieldDecorator('type', {
      initialValue: get(currentData, 'type', 'NOTICE'),
    });

    return (
      <Form {...formItemLayout} layout="horizontal">
        <Row gutter={24}>
          <Col span={12}>
            <FormItem label="信息内容">
              {getFieldDecorator('info', {
                initialValue: get(currentData, 'info', ''),
                rules: [
                  {
                    required: true,
                    message: '请输入信息内容',
                  },
                ],
              })(<Input maxLength={20} placeholder="最多输入20个字符" disabled={globalDisabled} />)}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="序号">
              {getFieldDecorator('rank_', {
                initialValue: get(currentData, 'rank_', ''),
                rules: [
                  {
                    required: true,
                    message: '请输入序号',
                  },
                ],
              })(<Input placeholder="请输入序号" disabled={globalDisabled} />)}
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

export default FormModal;
